layui.define(['table', 'form', 'admin', 'upload'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , form = layui.form
        , upload = layui.upload
        , admin = layui.admin;

    // 礼物类型选择
    // 豪华礼物显示上传动画
    form.on('select(gift_type)', function (data) {
        if (data.value == 1 || data.value == 2) {
            $("#animationArea").show();
        } else {
            $("#animationArea").hide();
        }
    });

    //
    table.render({
        elem: '#LAY-gift-manage'
        , url: '/admin/gift/getlist'
        , cols: [[
            { field: 'id', width: 70, title: 'ID', sort: true }
            , { field: 'sort', width: 60, title: '排序' }
            , { field: 'title', width: 150, title: '名称' }
            , {
                field: 'icon', title: '图标', width: 100, templet: function (d) {
                    if (d.icon) {
                        return "<img style='display: inline-block; width: auto; height: 100%;' src= '" + d.icon + "'>";
                    }
                    return '';
                }
            }
            , {
                field: '', minWidth: 150, title: '动画', templet: function (d) {
                    if (d.animat_type == 1) {
                        return "<img style='display: inline-block; width: auto; height: 100%;' src= '" + d.animation + "'>";
                    } else {
                        return d.animation
                    }
                }
            }
            , {
                field: '', width: 100, title: '动画时长', templet: function (d) {
                    return d.duration + " ms";
                }
            }
            , {
                field: '', width: 100, title: '礼物类型', templet: function (d) {
                    switch (d.type) {
                        case 0:
                            return '普通礼物';
                        case 1:
                            return '豪华礼物';
                        case 2:
                            return '活动礼物';
                        default:
                            return "";
                    }
                }
            }
            , {
                field: '', width: 100, title: '价格类型', templet: function (d) {
                    return d.price_type == 1 ? "金币" : "龙钻";
                }
            }
            , { field: 'price', width: 100, title: '价格' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-giftlist-gift' }
        ]]
        , page: false
        , limit: 0
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    //监听工具条
    table.on('tool(LAY-gift-manage)', function (obj) {
        if (obj.event === 'del') {
            var status = obj.data.status == 0 ? 1 : 0;
            var confirm_txt = status == 1 ? '确定要上架该礼物吗?' : '确定要下架该礼物吗?';
            layer.confirm(confirm_txt, function (index) {

                admin.req({
                    url: '/admin/gift/del_post'
                    , data: { "id": obj.data.id, "status": status }
                    , success(res) {
                        if (res.code == 0) {
                            table.reload("LAY-gift-manage");
                            layer.msg(res.msg, { icon: 1 });
                        } else {
                            layer.msg(res.msg, { icon: 5 });
                        }
                    }
                });
            });
        } else if (obj.event === 'edit') {
            layer.open({
                type: 2
                , title: '编辑'
                , content: '/admin/gift/edit?id=' + obj.data.id
                , maxmin: true
                , area: ['650px', '600px']
            });
        }
    });

    //上传图标
    var iconSrc = $('#LAY_iconImgSrc');
    upload.render({
        url: '/admin/index/noOperation'
        , elem: '#LAY_iconImgUpload'
        , auto: true
        , choose: function (obj) {
            layer.load();
            var choosefile;
            obj.preview(function (index, file, result) {
                choosefile = file;
            });
            admin.req({
                url: '/admin/gift/signForCos'
                , success: function (res) {
                    if (res.code == 0) {
                        var cos = new COS({
                            getAuthorization: function (options, callback) {
                                var credentials = res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    ExpiredTime: res.data.expiredTime
                                });
                            },
                            Domain: res.data.imgDomain,
                        });
                        cos.putObject({
                            Bucket: res.data.bucket,
                            Region: res.data.region,
                            Key: 'images/' + res.data.filename + choosefile.name,
                            Body: choosefile,
                        }, function (err, data) {
                            layer.closeAll('loading');
                            if (err) {
                                layer.msg("上传失败", { icon: 5 });
                            } else {
                                if (data.statusCode == 200) {
                                    iconSrc.val("https://" + data.Location);
                                } else {
                                    layer.msg("图片上传失败", { icon: 5 });
                                }
                            }
                        });
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.msg, { icon: 5 });
                    }
                }
            })
        }
    });

    //查看图标
    admin.events.coverImgPreview = function (othis) {
        var src = iconSrc.val();
        if (!src) {
            return layer.msg('请添加图片', { icon: 5 });
        }
        layer.photos({
            photos: {
                "title": "查看图标" //相册标题
                , "data": [{
                    "src": src //原图地址
                }]
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };

    //上传动画
    var animationSrc = $('#LAY_animationSrc');
    upload.render({
        url: '/admin/index/noOperation'
        , elem: '#LAY_animationUpload'
        , auto: true
        , accept: 'file'
        , exts: 'svga|svg|gif'
        , choose: function (obj) {
            layer.load();
            var choosefile;
            obj.preview(function (index, file, result) {
                choosefile = file;
            });
            admin.req({
                url: '/admin/gift/signForCos'
                , success: function (res) {
                    if (res.code == 0) {
                        var cos = new COS({
                            getAuthorization: function (options, callback) {
                                var credentials = res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    ExpiredTime: res.data.expiredTime
                                });
                            },
                            Domain: res.data.imgDomain,
                        });
                        cos.putObject({
                            Bucket: res.data.bucket,
                            Region: res.data.region,
                            Key: 'animations/' + res.data.filename + choosefile.name,
                            Body: choosefile,
                        }, function (err, data) {
                            layer.closeAll('loading');
                            if (err) {
                                layer.msg("上传失败", { icon: 5 });
                            } else {
                                if (data.statusCode == 200) {
                                    animationSrc.val("https://" + data.Location);
                                } else {
                                    layer.msg("上传失败", { icon: 5 });
                                }
                            }
                        });
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.msg, { icon: 5 });
                    }
                }
            })
        }
    });

    //查看图标
    admin.events.animationPreview = function (othis) {
        var src = animationSrc.val();
        if (!src) {
            return layer.msg('请添加图片', { icon: 5 });
        }
        layer.photos({
            photos: {
                "title": "查看图标" //相册标题
                , "data": [{
                    "src": src //原图地址
                }]
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };

    ////////////////////////////////  SEND-GIFT-LOG    ///////////////////////////

    table.render({
        elem: '#LAY-giftsend-manage'
        , url: '/admin/gift/getsendlist'
        , cols: [[
            { field: 'id', width: 100, title: 'ID', sort: true }
            , {
                field: '', width: 150, title: '赠送礼物', templet: function (d) {
                    if (gifts[d.giftid]) {
                        return gifts[d.giftid] + "(" + d.giftid + ")";
                    }

                    return '';
                }
            }
            , {
                field: '', width: 200, title: '赠礼用户', templet: function (d) {
                    if (d.user) {
                        return d.user.nick_name + "(" + d.user.id + ")";
                    }
                    return '未知用户';
                }
            }
            , {
                field: '', width: 200, title: '收礼用户', templet: function (d) {
                    return d.anchor ? d.anchor.nick_name + "(" + d.anchor.id + ")" : '';
                }
            }
            , { field: 'liveid', width: 150, title: '直播id' }
            , { field: 'count', width: 80, title: '数量' }
            , { field: 'unit_price', width: 100, title: '礼物单价' }
            , { field: 'spend', width: 100, title: '礼物总价' }
            , { field: 'actual_spend', width: 130, title: '礼物实收金额' }
            , { field: 'remark', width: 100, title: '备注' }
            , { field: 'create_time', minWidth: 180, title: '时间' }
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    ////////////////////////////////  user  send gift 单个用户赠送记录    ///////////////////////////

    table.render({
        elem: '#LAY-gift-usersend-manage'
        , url: '/admin/gift/getUserSendList?uid=' + $('#userId').val()
        , totalRow: true
        , cols: [[
            { field: 'id', width: 100, title: 'ID', sort: true }
            , {
                field: '', width: 150, title: '赠送礼物', totalRowText: '合计', templet: function (d) {
                    return d.gift ? d.gift.title + "(" + d.gift.id + ")" : '';
                }
            }
            , {
                field: '', width: 200, title: '收礼用户', templet: function (d) {
                    if (typeof d.anchor == 'undefined') {
                        return '';
                    }
                    return d.anchor.nick_name + "(" + d.anchor.id + ")";
                }
            }
            , { field: 'liveid', width: 150, title: '直播id' }
            , { field: 'count', width: 100, title: '数量', totalRow: true }
            , { field: 'actual_spend', width: 100, title: '总价', totalRow: true }
            // , {field: 'remark', width: 100, title: '备注'}
            , { field: 'create_time', minWidth: 180, title: '时间' }
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });


    exports('gift', {})
});

function input_num(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, "");
    obj.value = obj.value.replace(/^\./g, "");
    obj.value = obj.value.replace(/\.{2,}/g, ".");
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

    if (obj.value.indexOf(".") > 0 && obj.value.indexOf("0") > 2) {
        obj.value = parseFloat(obj.value);
    }
    if (obj.value.indexOf(".") > 0 && obj.value.lastIndexOf("0") > 2) {
        obj.value = parseFloat(obj.value);
    }
    if (obj.value.indexOf(".") <= 0 && obj.value != "") {
        obj.value = parseFloat(obj.value);
    }
}